/*****************************************************************************************
**  Author:dgz master
**  Contact：jiduxiong@dagongzao.com
**
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码

// import { type } from "os";
// import { Value } from "sass";
// import { json } from "stream/consumers";


import axios from 'axios'; // 确保这行存在！
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: "",
    gridBody: "",
    gridFooter: "",
    //新建、编辑弹出框扩展组件
    modelHeader: "",
    modelBody: "",
    modelRight: "",
    modelFooter: "",
    // sampling_reliability_qty:""
  },
  tableAction: "", //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  qualified_rate : 0,
  product_id : "",
  diandu_no : 0,
  methods: {
     //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
        //示例：在按钮的最前面添加一个按钮
        //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
        //     name: "按钮", //按钮名称
        //     icon: "el-icon-document", //按钮图标：https://element.eleme.cn/#/zh-CN/component/icon
        //     type: "primary", //按钮样式:https://element-plus.gitee.io/zh-CN/component/button.html
        //     //color:"#eee",//自定义按钮颜色
        //     onClick: function () {
        //       this.$Message.success("点击了按钮");
        //     }
        //   });
        //示例：设置修改新建、编辑弹出框字段标签的长度
        // this.boxOptions.labelWidth = 150;
        // this.test_kong()
        
    },
    data() {
      return {
        isLoading: false,
        // 其他数据...
      }
    },
    sendLowQualifiedRateEmail(qualified_rate, product_id, diandu_no) {
      const emailData = {
        QualifiedRate: String(qualified_rate), 
        ProductId: product_id,
        DianduNo: diandu_no,
        Type:"外观检验结单"
        // 可以根据需要添加更多邮件内容
      };

      // 调用你的邮件服务API
      //item.url = 'api/AmesSyncBiz/SyncProductionTask_CCD'  //后端代码中<ATkg.BizAppProject/Controllers/AmesSyncController.cs中的Route
      //axios.post('api/Email/SendEmail', emailData)
      console.log(emailData);
      axios.post('api/AmesSyncBiz/SyncPartnerName', emailData)
        .then(response => {
          //alert('低合格率警告邮件已发送！'); // 浏览器弹窗提示
          console.log('低合格率警告邮件已发送');
        })
        .catch(error => {
          // alert('发送邮件失败，请检查“预警邮箱”中是否维护对应的客户邮箱！或检查网络等原因！'); // 浏览器弹窗提示
          console.error('未发送邮件', error);
        });
    },
    formatCurrentTime() {
      console.log("时间函数！！！")
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
    onInited() {      
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      this.sampling_reliability_qty = 0
      this.songce_befo = 0      
      console.log("this.buttons",this.buttons)      
      let button_all = this.buttons
      let anniu_pro = []
      for(let i=0;i < button_all.length;i++){
        console.log(button_all[i])
        anniu_pro.push(button_all[i]["name"])
      }
      console.log("anniu_pro",anniu_pro)
      if(anniu_pro.length > 5){
        this.test_kong(anniu_pro)
      }else{
        if(anniu_pro.includes("删除")){
          console.log("不获取MES数据！！！")
        }else{
          this.test_kong(anniu_pro)
        } 
      }
           
      this.boxButtons.unshift({
        name: "计算",
        icon: "el-icon-plus",
        type: "primary",
        onClick: () =>{
          this.complete(anniu_pro);
        }
      })
     
    },
    deal_data(table_name,coun_name){
      if(this.editFormFields[table_name] == ""){
        coun_name += 0
      }else{
        coun_name += parseInt(this.editFormFields[table_name])
      }
      return coun_name
    },
    complete(anniu_pro){
      const tableName = this.editFormFields["lie_W"]
      console.log(tableName)
      console.log("进入计算方法！！！")
      console.log("this.buttons",this.buttons,anniu_pro)
      console.log(this.sampling_reliability_qty,"sampling_reliability_qty")
      console.log(this.songce_befo,"songce_befo")
      var can_zonghe = 0
      var kefan_zonghe = 0
      can_zonghe = this.deal_data("light_point",can_zonghe)
      can_zonghe = this.deal_data("lie_W",can_zonghe)
      can_zonghe = this.deal_data("sha_yan",can_zonghe)
      can_zonghe = this.deal_data("gui_you",can_zonghe)
      can_zonghe = this.deal_data("ct_no",can_zonghe)
      can_zonghe = this.deal_data("yang_hua",can_zonghe)
      can_zonghe = this.deal_data("dao_heng",can_zonghe)
      can_zonghe = this.deal_data("chuzhi",can_zonghe)
      can_zonghe = this.deal_data("all_chicun",can_zonghe)
      can_zonghe = this.deal_data("beng_side",can_zonghe)
      can_zonghe = this.deal_data("dao_C",can_zonghe)
      can_zonghe = this.deal_data("black_side",can_zonghe)
      can_zonghe = this.deal_data("all_keb",can_zonghe)
      can_zonghe = this.deal_data("all_mk",can_zonghe)
      can_zonghe = this.deal_data("song_ce",can_zonghe)
      can_zonghe = this.deal_data("jb_lost",can_zonghe)
      can_zonghe = this.deal_data("qipao",can_zonghe)
      can_zonghe = this.deal_data("ducengsec",can_zonghe)
      can_zonghe = this.deal_data("jieheli_no",can_zonghe)
      can_zonghe = this.deal_data("ducan",can_zonghe)
      can_zonghe = this.deal_data("aokeng",can_zonghe)
      can_zonghe = this.deal_data("pengt_jq",can_zonghe)
      can_zonghe = this.deal_data("pengT_zw",can_zonghe)
      can_zonghe = this.deal_data("pentu_yw",can_zonghe)
      can_zonghe = this.deal_data("r_kb",can_zonghe)
      can_zonghe = this.deal_data("qian_kb",can_zonghe)
      can_zonghe = this.deal_data("hou_kb",can_zonghe)
      
      kefan_zonghe = this.deal_data("kf_ex",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_ducse",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_duchh",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_qipao",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_cc",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_kb",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_ak",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_jq",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_yw",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_zw",kefan_zonghe)
      kefan_zonghe = this.deal_data("kf_dd",kefan_zonghe)

      console.log('this.anniu_pro["删除"]',anniu_pro)
      if(anniu_pro.includes("删除")){
        console.log("有删除权限")    //有编辑修改权限
        var fanhui_qtyy = can_zonghe + kefan_zonghe
        fanhui_qtyy += parseInt(this.editFormFields["ok_qty"])
        var liiushi_qty = 0
          if(this.editFormFields['y_h_qty'] == ""){
              liiushi_qty += 0
          }else{
              liiushi_qty = parseInt(this.editFormFields['y_h_qty']) - fanhui_qtyy
          }          
          this.editFormFields['c_total'] = can_zonghe
          this.editFormFields['kf_total'] = kefan_zonghe
          this.editFormFields['fh_qty'] = fanhui_qtyy
          this.editFormFields['lost_qty'] = liiushi_qty
      }else{
        console.log("没有删除权限")  //没有编辑修改权限
        var songce_ = 0
        if(this.editFormFields['song_ce'] == ''){
            songce_ = 0 + this.sampling_reliability_qty                    
        }else{
            if(parseInt(this.editFormFields['song_ce']) == this.songce_befo){
                songce_ = this.songce_befo
            }else{
                songce_ = parseInt(this.editFormFields['song_ce']) + parseInt(this.sampling_reliability_qty)
            }        
        }
        this.songce_befo = songce_
        var fanhui_qtyy = can_zonghe + kefan_zonghe
        if(this.editFormFields["ok_qty"] == ""){
          alert("合格数未填写！！！")
        }else{
          fanhui_qtyy += parseInt(this.editFormFields["ok_qty"])
          var liiushi_qty = 0
          if(this.editFormFields['y_h_qty'] == ""){
              liiushi_qty += 0
          }else{
              liiushi_qty = parseInt(this.editFormFields['y_h_qty']) - fanhui_qtyy
          }
          this.editFormFields['song_ce'] = songce_
          this.editFormFields['c_total'] = can_zonghe + songce_
          this.editFormFields['kf_total'] = kefan_zonghe
          this.editFormFields['fh_qty'] = fanhui_qtyy
          this.editFormFields['lost_qty'] = liiushi_qty
        }
      }
      for(let i=0; i<this.editFormOptions.length; i++){
        for(let j=0; j<this.editFormOptions[i].length;j++){
          this.editFormOptions[i][j]["disabled"] = true
        }
      }
      this.qualified_rate = ((parseInt(this.editFormFields['ok_qty']) / parseInt(this.editFormFields['fh_qty']))*100).toFixed(2)
      this.diandu_no = this.editFormFields['lot']
      this.product_id = this.editFormFields["pro_code"]
      console.log("???????",this.qualified_rate,this.diandu_no,this.product_id)
    },
    test_kong(item) {      
      console.log("::::::::::::",item)
      
      this.editFormOptions.forEach(x => {
        x.forEach(option => {
          console.log("LLL")
            if (option.field == "order_name") {
                option.onKeyPress = $event => {
                    //监听回车事件
                    if ($event.keyCode == 13) {
                        console.log($event.keyCode) ;
                        console.log("回车事件") ;
                        console.log("KKKKKKKKK");
                        const formattedTime = this.formatCurrentTime();
                        this.editFormFields["data_time"] = formattedTime
                        // this.isLoading = true;
                        // 创建loading实例
                        const loadingInstance = this.$loading({
                          lock: true,
                          text: '同步MES数据中···',
                          spinner: 'el-icon-loading',
                          background: 'rgba(247, 237, 237, 0.7)'
                        });
                        // //  使用get方法调用接口+传参数
                        this.http.get('api/table_wgjy/SyncProductionTask_wgjy_get',
                          {name_order:this.editFormFields.order_name}).then((reslut) => {
                          console.log("GGGGG");
                          console.log(this.editFormFields.order_name);
                          console.log('同步成功:', reslut);
                          loadingInstance.close();
                          this.editFormFields.pro_gen = reslut["rows"][0]["partner"]
                          this.editFormFields.lot = reslut["rows"][0]["raw_lot_id"]
                          this.editFormFields.re_lot = reslut["rows"][0]["recycle_grade"]
                          this.editFormFields.guige_cc = reslut["rows"][0]["prodcut_spec"]
                          this.editFormFields.pro_code = reslut["rows"][0]["product"]
                          this.editFormFields.per_weight = reslut["rows"][0]["piece_weight"]
                          this.editFormFields.gred = reslut["rows"][0]["grade"]
                          this.editFormFields.y_h_qty = reslut["rows"][0]["raw_resume_stock_qty"]
                          this.sampling_reliability_qty = reslut["rows"][0]["sampling_reliability_qty"]
                          
                          // this.editFormFields.pro_gen = reslut["rows"][0]["partner"]
                          // this.editFormFields.pro_gen = reslut["rows"][0]["partner"]
                        }).catch((error) => {
                            console.error('同步失败:', error);
                            loadingInstance.close();
                        });

                        // //  使用post方法调用接口+传参数
                        // this.http.post('api/table_wgjy/SyncProductionTask_wgjy_post',                           
                        //   {name_order:this.editFormFields.order_name}).then((reslut) => {
                        //   console.log("GGGGG");
                        //   console.log(this.editFormFields.order_name);
                        //   console.log('同步成功:', reslut);
                        //   this.editFormFields.pro_gen = reslut["rows"][0]["partner"]
                        //   this.editFormFields.lot = reslut["rows"][0]["raw_lot_id"]
                        //   this.editFormFields.re_lot = reslut["rows"][0]["recycle_grade"]
                        //   this.editFormFields.guige_cc = reslut["rows"][0]["prodcut_spec"]
                        //   this.editFormFields.pro_code = reslut["rows"][0]["product"]
                        //   this.editFormFields.per_weight = reslut["rows"][0]["piece_weight"]
                        //   this.editFormFields.gred = reslut["rows"][0]["grade"]
                        //   this.editFormFields.y_h_qty = reslut["rows"][0]["raw_resume_stock_qty"]
                        // }).catch((error) => {
                        //     console.error('同步失败:', error);
                        // });
                        // option.url = 'api/table_wgjy/SyncProductionTask_wgjy'
                        return;
                    }

                    setTimeout(() => {
                        // console.log(this.editFormFields.字段);
                        // //也可给其他字段设置值(实时计算)
                        // this.editFormFields.字段1=this.editFormFields.字段2+123
                    }, 100);
                    //获取表单其他字段的值或者设置值：  this.editFormFields.字段
                }
            }
        })
    })
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    delBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
   addAfter(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      //添加后刷新字典
      this.sendLowQualifiedRateEmail(this.qualified_rate, this.product_id, this.diandu_no);
      return true;
    },
    updateAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典
      
      return true;
    },
    delAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典      
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=="Add";
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段="xxx";
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      for(let i=0; i<this.editFormOptions.length; i++){
        for(let j=0; j<this.editFormOptions[i].length;j++){
          this.editFormOptions[i][j]["disabled"] = false
        }
      }
    }
  }
};
export default extension;
